package com.leyou.gateway.filters;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.JwtConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 拦截用户请求，并刷新有效期
 */
@Slf4j
@Order
@Component
public class LoginFilter implements GlobalFilter {

    @Autowired
    private JwtUtils jwtUtils;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try{
            // 获取Request
            ServerHttpRequest request = exchange.getRequest();
            // 获取jwt
            // 获取所有的cookie
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            // 取出我们需要的cookie
            HttpCookie cookie = cookies.getFirst(JwtConstants.COOKIE_NAME);
            if (cookie == null){
                //没有登陆 放行
                return chain.filter(exchange);
            }
            //校验token是否有效
            String jwt = cookie.getValue();

            Payload payload = jwtUtils.parseJwt(jwt);
            UserDetails userDetail = payload.getUserDetail();
            //刷新jwt
            jwtUtils.refreshJwt(userDetail.getId());
            log.info("用户{}正在访问{}", userDetail.getUsername(), request.getURI().getPath());
        }catch (Exception e){
            //解析失败 token有误
            log.error("刷新token失败");
        }
        //放行
        return chain.filter(exchange);
    }

}
